package com.tpc.yaoxpt.utils;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.tpc.yaoxpt.main.LogModule;
import com.tpc.yaoxpt.main.MainController;
import com.tpc.yaoxpt.service.SignService;
import javafx.application.Platform;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

@Slf4j
public class HttpClientUtil {

    final static LogModule logModule = new LogModule();

    final static SignService signService = new SignService();
    public static String doPost(String url, JSONObject json){

        String timestamp = DateUtil.format(new Date(),"yyyyMMddHHmmss");
        Map<String, String> ptConfig = null;
        try {
            ptConfig = FileUtil.getPTConfig();
        } catch (IOException e) {
//            logModule.appendLogInfo( "\n" + e.getMessage());
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    MainController.staticLogText.appendText("\n" + e.getMessage());
                }
            });
            throw new RuntimeException(e);
        }

        WebClient webClient = WebClient.create();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("ApiKey",ptConfig.get("APIKEY"));
        headers.set("secretKey",ptConfig.get("SECRETKEY"));
        headers.set("Timestamp",timestamp);
        headers.set("Sign",signService.getSign(timestamp));
        String responseBody = "";
        try {
            responseBody = webClient.post()
                    .uri(url)
                    .headers(httpHeaders -> httpHeaders.putAll(headers))
                    .body(BodyInserters.fromValue(json))
                    .retrieve()
                    .bodyToMono(String.class)
                    .block();
        }catch (Exception e){
            log.info("错误请求信息：",e.getMessage());
        }

        return responseBody;
    }
}
